package com.winshare.saleAssistant.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.winshare.saleAssistant.config.SmsConfig;
import com.winshare.saleAssistant.domain.dto.req.SmsParamDTO;
import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.service.SmsService;
import com.winshare.saleAssistant.util.JacksonUtils;
import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements SmsService {

    private final SmsConfig smsConfig;

    public SmsServiceImpl(SmsConfig smsConfig) {
        this.smsConfig = smsConfig;
    }

    @Override
    public void sendSms(String captchaCode,String phone) {
        DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(),smsConfig.getAccessKeyId(),
                smsConfig.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsConfig.getDomain());
        request.setSysVersion(smsConfig.getSysVersion());
        request.setSysAction(smsConfig.getSysAction());
        request.putQueryParameter("RegionId",smsConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers",phone);
        request.putQueryParameter("SignName",smsConfig.getSignName());
        request.putQueryParameter("TemplateCode",smsConfig.getTemplateCode());
        request.putQueryParameter("TemplateParam", JacksonUtils.writeValueAsString(new SmsParamDTO(captchaCode)));
        try {
            CommonResponse response = client.getCommonResponse(request);
        } catch (ServerException e){
            throw new BusinessException(e.getMessage());
        } catch (ClientException e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
